package com.mmd.parkingspringboot.config;

import com.mmd.parkingspringboot.config.JWTUtil;
import com.mmd.parkingspringboot.config.JwtAuthenticationTokenFilter;
import com.mmd.parkingspringboot.model.LoginUser;
import com.mmd.parkingspringboot.model.Manage;
import com.mmd.parkingspringboot.model.User;
import com.mmd.parkingspringboot.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public Result login(@RequestBody Manage user){//前端一般是json格式传递，使用请求体接收
        /** 通过authenticationManager.authenticate()进行认证，
         * 其底层会调用UserDetailsService接口的loadUserByUsername方法，通过传入的user.getUserName(),user.getPassword()
         *与UserDetails接口的  String getPassword() String getUsername(); 方法其实现类LoginUser的返回值进行对比
         * 将UserDetails接口实现类进行封装到 Authentication接口中
         *  */

        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(user.getManagePhone(),user.getManagePassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        /** 如果为null 则上一步认证不成功*/
        if (Objects.isNull(authenticate)){

            throw  new RuntimeException("登录失败");
        }
        /**认证成功则获取其封装的LoginUser 注意这个LoginUser的getUser就是登录用户的完整信息 不懂的看LoginImpl中*/
        LoginUser getUser = (LoginUser) authenticate.getPrincipal();
        /*获取登录用户的id*/
        String id = getUser.getUser().getManageId().toString();
        /*使用JWT生成token*/
        String token = JWTUtil.createJWT(id);
        /*将登录的用户信息转为json格式存入redis中*/
        JwtAuthenticationTokenFilter.userLoginMap.put(id, getUser);
        /*携带token响应到浏览器*/
        return Result.ok().data("token",token).data("message", getUser.getUser());
    }

}
